package com.hzz.gulimall.ssoclient.controller;

import   org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
public class ClientHelloController {
    /**
     * 无需登录就能访问的
     *
     * @return
     */
    @Value("${sso.server.url}")
    String ssoServerUrl;

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     *  1.要能感知到在ssoserver中登录成功调回来的
     *  2.登录成功机会带上token  非必须参数
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token",required = false)String token){
        // todo 去ssoserver 获取当前token真正的对应的用户信息
        //认证服务返回的token
        if(!StringUtils.isEmpty(token)){
            RestTemplate restTemplate = new RestTemplate();
            //restTemplate 基于restful风格的远程调用
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        //关键是要判断session中是否有用户
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client1.com:8081/employees";
        }else {
            ArrayList<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }


    }

}
